<template>
	<view>
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">全部订单</block>
		</cu-custom>
		<!-- 顶部导航 -->
		<view>
			<!-- 顶部导航 -->
			<view class="topTabBar" :style="{position:headerPosition}">
				<view class="grid" v-for="(grid,tbIndex) in orderType" :key="tbIndex" @tap="showType(tbIndex)">
					<view class="text" :class="[tbIndex==tabbarIndex?'on':'']">{{grid}}</view>
				</view>
			</view>
			<!-- 考虑非APP端长列表和复杂的DOM使用scroll-view会卡顿，所以漂浮顶部选项卡使用page本身的滑动 -->
			<view class="order-list">
				<view class="list">
					<view class="row" v-if="total != 0" v-for="(row,index) in list" :key="index">
						<view class="top">
							<view class="order-num">下单时间:{{row.createTime}}({{row.orderStatus}})</view>
							<view class="type received" v-if="row.status == 1"> 已审核</view>
							<view class="type unpaid" v-else> 未审核</view>
						</view>
						
						<!-- 表头行 -->
						<uni-row style="color:#A5673F;font-size: small;">
							<uni-col :xs="12">
								<view>名称</view>
							</uni-col>
							<uni-col :xs="3">
								<view style="text-align: right;">单价</view>
							</uni-col>
							<uni-col :xs="4">
								<view style="text-align: right;">数量</view>
							</uni-col>
							<uni-col :xs="5">
								<view style="text-align: right;">小计</view>
							</uni-col>
						</uni-row>
						
						
						<uni-row style="color:#555555;font-size: small;" v-for="(item,j) in row.orderDetailEntities" :key="j" v-if="item.materialCode != '715002' && item.materialCode != '715001' ">
							
							<uni-col :xs="12">
								<view>{{item.materialName}}</view>
							</uni-col>
							
							<uni-col :xs="3">
								<view style="text-align: right;" class="price">{{parseFloat(item.price / item.num).toFixed(2)}}</view>
							</uni-col>
							
							<uni-col :xs="4">
								<view style="text-align: right;" v-if="item.materialName != '香葱'">{{item.num}}</view>
								<view style="text-align: right;" v-else>{{parseFloat(item.num*4.5/500).toFixed(3)}}</view>
							</uni-col>
							
							<uni-col :xs="5">
								<view class="price" :id="row.id" style="text-align: right;" :data-price="item.price" >
									{{parseFloat(item.price).toFixed(2)}}
								</view>
							</uni-col>
							
						</uni-row>

						<view class="order-memo">{{row.fnote}}</view>
						
						<view class="btns">
							<view class="bill" style="font-size: small;">合计:{{parseFloat(row.amount).toFixed(2)}}元</view>
							<view class="con">
								<block v-if="checkOrder(row)">
									<view class="default" @tap="cancelOrder(row)">取消</view>
								</block>
							</view>
						</view>
						
					</view>
					<br>
					<view class="onorder" v-if="total == 0">
						<image style="width: 160px; height: 160px;display: block;margin: 0 auto;" src="../../static/images/noCart.png"></image>
						<view class="text">
							您还没有订单......
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		uniRow,
		uniCol
	} from '@dcloudio/uni-ui'

	import {
		formatDate
	} from '@/server/api'

	import {
		orderlistActionApi,
		cancelOrderApi,
		receiveOrderApi
	} from "@/server/config.js";
	export default {
		components: {
			uniRow,
			uniCol
		},

		onLoad() {
			this.tabbarIndex = 0;
			this.fetData()
		},
		onShow() {
			//his.showType();
		},
		onReachBottom() {
			this.page = this.page + 1;
			if (this.page > this.total) {
				return false;
			}
			this.fetData();
		},
		data() {
			return {
				img_blank: "../static/images/no_order.png",
				headerPosition: "",
				orderType: ["全部", "未审核", "已审核"],
				//订单列表 演示数据
				orderList: [],
				list: [],
				tabbarIndex: 0,
				page: 1,
				pageSize: 10,
				total: 0,
			};
		},
		onPageScroll(e) {
			//return;
			//兼容iOS端下拉时顶部漂移
			if(e.scrollTop > 0){
				this.headerPosition = 'fixed'
			}else{
				this.headerPosition = ''
			}
			//this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
			
		},

		methods: {
			async fetData() {
				let pars = {
					pageSize: this.pageSize,
					pageNo: this.page
				}
				if (this.tabbarIndex > 0) {
					pars['status'] = this.tabbarIndex - 1
				}
				let result = await orderlistActionApi(pars);
				this.orderList = result.data.records
				this.total = result.data.totalPage
				
				if(this.page > 1){
					this.list = this.list.concat(this.orderList)
				}else{
					this.list = this.orderList
				}
			},
			checkOrder(row) {
				if (row.status == 0) {
					/* 	let now = new Date()
						let rule = Date.parse(formatDate(new Date()) + ' 15:30:00')
						let ruleEnd = Date.parse(formatDate(new Date()) + ' 18:00:00')
						//今日的15:30到18:00之间不能删除订单
						if (now - rule > 0 && now - ruleEnd < 0) {
							return false
						} 
					*/
					return true
				}
				return false
			},
			showType(tbIndex) {
				this.page = 1
				this.tabbarIndex = tbIndex;
				this.getOrderList();
			},
			cancelOrder(row) {
				let _this = this
				uni.showModal({
					title: "取消订单",
					content: "确定取消此订单？",
					success: async res => {
						if (res.confirm) {
							const res = await cancelOrderApi(row.id);
						} else if (res.cancel) {
						}
					}
				});
			},
			showStatus(row) {
				let payMsg = ''
				let msg = '';
				let _this = this;

				if (row.DocumentStatus) {
					if (row.DocumentStatus == 'A') {
						msg = '未审核'
					}
					if (row.DocumentStatus == 'C') {

						if (row.SaleOrderEntry.some(p => p.AllAmount != p.ReceiveAmount)) {
							payMsg = '未付款'
						} else {
							payMsg = '已付款'
						}

						if (row.SaleOrderEntry.some(p => p.DeliveryStatus == 'A')) {
							msg = '未发货'
						}

						if (row.SaleOrderEntry.some(p => p.DeliveryStatus == 'B')) {
							msg = '部分发货'
						}

						if (row.SaleOrderEntry.some(p => p.DeliveryStatus == 'C')) {
							msg = '已发货'
						}
					}
				}
				return payMsg + ' ' + msg
			},
			getOrderList() {
				/** 
				 * 全部、
				 * 未审核（刚下的订单没有审核）
				 * 未付款（审核过了没有付款）
				 * 未发货（付款了，没发货）
				 * 每个订单的 DELIVERYSTATUS: ‘A’:未发货 ‘B’：部分发货 ‘C’：已发货
				每个订单的 ALLAMOUNT不等于RECEIVEAMOUNT，就是没付款
				 */

				this.fetData()

				// let _this = this;

				// if (this.tabbarIndex == 0) {
				// 	this.list = this.orderList
				// }

				// //未审核
				// if (this.tabbarIndex == 1) {
				// 	this.list = this.orderList.filter(item => item.status === 0);
				// }

				// //审核
				// if (this.tabbarIndex == 2) {
				// 	this.list = this.orderList.filter(item => item.status === 1);
				// }

				// //每个订单的 ALLAMOUNT不等于RECEIVEAMOUNT，就是没付款
				// if (this.tabbarIndex == 2) {
				// 	this.list = []
				// 	this.orderList.forEach(function(order) {
				// 		if (order.SaleOrderEntry.some(p => p.AllAmount != p.ReceiveAmount)) {
				// 			_this.list.push(order)
				// 		}
				// 	})
				// }

				// //每个订单的 DELIVERYSTATUS: ‘A’:未发货 ‘B’：部分发货 ‘C’：已发货
				// if (this.tabbarIndex == 3) {
				// 	this.list = []
				// 	this.orderList.forEach(function(order) {
				// 		if (o元rder.SaleOrderEntry.some(p => p.DeliveryStatus == 'A')) {
				// 			_this.list.push(order)
				// 		}
				// 	})
				// }

				// if (this.tabbarIndex == 3) {
				// 	order_list = order_list.filter(item => item.type === 'unreceived');
				// }

				// if (this.tabbarIndex == 4) {
				// 	order_list = order_list.filter(item => item.type === 'received');
				// }


				// const data = await orderlistActionApi({
				//     openId: uni.getStorageSync("openId"),
				//     page: this.page,
				//     status: this.tabbarIndex //订单状态
				//         //   user_id: uni.getStorageSync("user_id")
				// });
				// this.list=data.data.order_list
				// console.info(data.data.order_list);
				// this.total = data.data.pagetotal;
				// console.log(this.total);
				// if (first) {
				// 	this.list = order_list;
				// } else {
				// 	this.list = this.list.concat(data.data.order_list);
				// }


				//this.showType(this.tabbarIndex);
			},
			cancelOrder(row) {
				uni.showModal({
					title: "取消订单",
					content: "确定取消此订单？",
					success: res => {
						if (res.confirm) {
							console.log("用户点击确定");
							this.doCancelOrder(row.id);
						} else if (res.cancel) {
							console.log("用户点击取消");
						}
					}
				});
			},
			async doCancelOrder(order_id) {
				const res = await cancelOrderApi(order_id);
				if (res.statusCode == 400) {

					let errs = res.data.errors;
					errs.forEach(p => {
						if (p.code == "CM009") {
							uni.showToast({
								title: p.message, //提示的内容,
								duration: 2000, //延迟时间,
								icon: "none",
								mask: true, //显示透明蒙层，防止触摸穿透,
								success: res => {}
							});
							return
						}
					})
				}

				if (res.statusCode == 200) {
					this.fetData()
				}
			},


			doReceive(first) {
				uni.navigateTo({
					url: "/apiMember/orderreceive/main"
				});
			}
		},

	};
</script>

<style lang="scss">
	@import "./style.scss";
</style>
